<template>
    <div>
        <!-- <TableSearch :query="query" :options="searchOpt" :search="handleSearch" /> -->
        <div class="container">
            <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
                :delFunc="handleDelete" :changePage="changePage" :editFunc="handleEdit">
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click="visibleMsg = true">添加</el-button>
                </template>
                <template #is_push="{ rows }">
                    <el-tag type="success" v-if="rows.is_push">是</el-tag>
                    <el-tag type="danger" v-else>否</el-tag>
                </template>
                <template #image="{ rows }">
                    <el-image style="width: 60px; height: 60px" :src="rows.full_image" fit="cover" />
                </template>
                <template #file="{ rows }">
                    <el-icon v-if="rows.file">
                        <Files />
                    </el-icon>
                    <span v-else>-</span>
                </template>
                <template #play="{ rows }">
                    <el-button type="primary" size="small" @click="setCallback(rows)">推送</el-button>
                    <el-popconfirm title="此操作会删除，是否确认操作?" @confirm="deleteCallback(rows)">
                        <template #reference>
                            <el-button type="danger" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                    <el-button type="warning" size="small" @click="handleEditBot(rows)">编辑</el-button>
                </template>
            </TableCustom>
        </div>
        <el-dialog title="添加消息" v-model="visibleMsg" width="80%" destroy-on-close :close-on-click-modal="false"
            @close="closeDialog">
            <div class="robot">
                <div class="le">消息</div> <el-input v-model="addMsg.message" :rows="3" type='textarea'
                    placeholder="请输入消息" />
            </div>
            <div class="robot">
                <div class="le">图片</div>
                <el-input v-model="addMsg.image" placeholder="请点击下方框上传图片" disabled />
            </div>

            <div class="robot">
                <div class="le" style="width: 140px;"></div>
                <el-upload action="#" list-type="picture-card" ref="uploadRef" :auto-upload="false" :multiple="false"
                    :file-list="fileList" :limit="1" :on-change="uploadChange" :on-remove="handleRemove">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <template #file="{ file }">
                        <div>
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                            <span class="el-upload-list__item-actions">
                                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                </span>
                            </span>
                        </div>
                    </template>
                </el-upload>

            </div>
            <div class="robot">
                <div class="le">文件</div> <el-input v-model="addMsg.file" placeholder="请输入上传文件" disabled />
                <el-upload ref="uploadRef1" class="upload-demo" :show-file-list="false" :on-change="uploadChangeFile"
                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :auto-upload="false">
                    <el-button class="ml-3" type="success" @click="submitUpload" style="margin-left :10px; ">
                        上传文件
                    </el-button>
                </el-upload>
            </div>

            <div class="robot">
                <div class="le">左边按钮标题</div> <el-input v-model="addMsg.left_title" placeholder="请输入左边按钮标题" />
            </div>
            <div class="robot">
                <div class="le">左边按钮链接</div> <el-input v-model="addMsg.left_link" placeholder="请输入左边按钮链接" />
            </div>
            <div class="robot">
                <div class="le">右边按钮标题</div> <el-input v-model="addMsg.right_title" placeholder="请输入右边按钮标题" />
            </div>
            <div class="robot">
                <div class="le">右边按钮链接</div> <el-input v-model="addMsg.right_link" placeholder="请输入右边按钮链接" />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitMsg">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 推送消息 -->
        <el-dialog v-model="dialogVisibleMsg" title="推送消息" width="50%">
            <div>
                <TableCustom :columns="columnsBot" :tableData="tableDataBot" :total="pageBot.total">
                    <template #play="{ rows }">
                        <el-button type="warning" size="small" @click="sendMsg(rows)">推送</el-button>
                        <el-button type="danger" size="small" @click="deleteSend(rows)">删除推送</el-button>
                    </template>
                </TableCustom>
            </div>

        </el-dialog>

    </div>
</template>

<script setup lang="ts">
    import { ref, reactive } from 'vue';
    import { ElMessage } from 'element-plus';
    import { CirclePlusFilled } from '@element-plus/icons-vue';
    import { User } from '@/types/user';
    import { agentMessageList, agentUpload, agentAddMessage, agentPushMessage, agentDelMessage, agentDelPushMessage, agentEditMessage, agentBotList } from '@/api';
    import TableCustom from '@/components/table-custom.vue';
    import TableDetail from '@/components/table-detail.vue';
    import TableSearch from '@/components/table-search.vue';
    import { FormOption, FormOptionList } from '@/types/form-option';

    // 查询相关
    const query = reactive({
        id: '',
    });
    const searchOpt = ref < FormOptionList[] > ([
        { type: 'input', label: '机器人ID:', prop: 'id' }
    ])
    const handleSearch = () => {

        changePage(1);
    };
    let visibleMsg = ref(false)
    // 表格相关
    let columns = ref([
        { prop: 'id', label: '消息ID', width: 120 },
        { prop: 'message', label: '消息内容', width: 120 },
        { prop: 'image', label: '图片' },
        { prop: 'file', label: '文件' },
        { prop: 'left_title', label: '左边按钮标题' },
        { prop: 'left_link', label: '左边按钮链接' },
        { prop: 'right_title', label: '右边按钮标题' },
        { prop: 'right_link', label: '右边按钮链接' },
        { prop: 'is_push', label: '推送' },
        { prop: 'create_date', label: '创建时间', width: 160 },
        { prop: 'update_date', label: '更新时间', width: 160 },

        { prop: 'play', label: '操作项', fixed: 'right', width: 230 }
    ])
    let columnsBot = ref([
        { prop: 'id_str', label: '机器人ID', width: 120 },
        { prop: 'name', label: '机器人名称', width: 120 },
        { prop: 'key', label: '机器人KEY' },
        { prop: 'play', label: '操作项', fixed: 'right', width: 160 }
    ])

    let addMsg = ref({
        id: '',
        message: '',
        file: '',
        image: '',
        left_title: '',
        left_link: '',
        right_title: '',
        right_link: '',
    })

    const page = reactive({
        page: 1,
        limit: 10,
        total: 0
    })
    const pageBot = reactive({
        page: 1,
        limit: 10,
        total: 0
    })
    const tableData = ref < User[] > ([]);
    const tableDataBot = ref < User[] > ([]);
    const getData = async () => {
        const res = await agentMessageList(page)
        tableData.value = res.data.data;
        page.total = res.data.total
    };
    const getDataBot = async () => {
        const res = await agentBotList(page)
        tableDataBot.value = res.data.data;
        pageBot.total = res.data.total
    };

    getData();
    getDataBot()
    const changePage = (val: number) => {
        page.page = val;
        getData();
    };
    // 图片预览相关
    const dialogImageUrl = ref('')
    const dialogVisible = ref(false)
    const dialogVisibleMsg = ref(false)
    const disabled = ref(false)
    const uploadRef = ref(null);
    const uploadRef1 = ref(null)
    const fileList = ref([]);
    const handleRemove = (file) => {
        uploadRef.value.clearFiles();
    }
    const uploadChange = async (data) => {
        console.log(data, '上传的文件数据');
        let fromData = new FormData();
        fromData.append('file', data.raw);
        let res = await agentUpload(fromData);
        if (res.code == 1) {
            console.log(res.data, '上传的图片数据');

            addMsg.value.image = res.data.url
            ElMessage.success('上传成功');
        } else {
            ElMessage.error(res.msg);
        }
    }
    const submitUpload = () => {
        uploadRef1.value.submit()
    }
    // 上传文件
    const uploadChangeFile = async (data) => {
        let fromData = new FormData();
        fromData.append('file', data.raw);
        let res = await agentUpload(fromData);
        if (res.code == 1) {
            addMsg.value.file = res.data.url
            ElMessage.success('上传成功');
        } else {
            ElMessage.error(res.msg);
        }
    }
    // 新增/编辑弹窗相关
    let options = ref < FormOption > ({
        labelWidth: '100px',
        span: 12,
        list: [
            { type: 'input', label: '用户名', prop: 'name', required: true },
            { type: 'input', label: '手机号', prop: 'phone', required: true },
            { type: 'input', label: '密码', prop: 'password', required: true },
            { type: 'input', label: '邮箱', prop: 'email', required: true },
            { type: 'input', label: '角色', prop: 'role', required: true },
        ]
    })
    const visible = ref(false);
    const isEdit = ref(false);
    const rowData = ref({});
    const handleEdit = (row: User) => {
        rowData.value = { ...row };
        isEdit.value = true;
        visible.value = true;
    };
    const updateData = () => {
        closeDialog();
        getData();
    };

    let handleEditBot = (data) => {
        fileList.value = [{
            name: 'example-image.jpg',
            url: data.full_image
        }];
        addMsg.value = {
            ...data
        }
        console.log(addMsg.value, '??');
        visibleMsg.value = true
    }
    const closeDialog = () => {
        visibleMsg.value = false;
        addMsg.value = {
            id: '',
            message: '',
            file: '',
            image: '',
            left_title: '',
            left_link: '',
            right_title: '',
            right_link: '',
        }

    };

    // 查看详情弹窗相关
    const visible1 = ref(false);
    const viewData = ref({
        row: {},
        list: []
    });
    const handleView = (row: User) => {
        viewData.value.row = { ...row }
        viewData.value.list = [
            {
                prop: 'id',
                label: '用户ID',
            },
            {
                prop: 'name',
                label: '用户名',
            },
            {
                prop: 'password',
                label: '密码',
            },
            {
                prop: 'email',
                label: '邮箱',
            },
            {
                prop: 'phone',
                label: '电话',
            },
            {
                prop: 'role',
                label: '角色',
            },
            {
                prop: 'date',
                label: '注册日期',
            },
        ]
        visible1.value = true;
    };

    // 删除相关
    const handleDelete = (row: User) => {
        ElMessage.success('删除成功');
    }

    // 机器人
    const submitMsg = async () => {
        if (addMsg.value.id) {
            let res = await agentEditMessage(addMsg.value)
            if (res.code == 1) {
                getData();
                ElMessage.success(res.msg);
                closeDialog();
            }
        } else {
            let res = await agentAddMessage(addMsg.value)
            if (res.code == 1) {
                getData();
                ElMessage.success(res.msg);
                closeDialog();
            }
        }

    }
    // 设置回调
    let BotId = ref('')
    const setCallback = async (data) => {
        dialogVisibleMsg.value = true;
        BotId.value = data.id;
    }
    // 推送消息
    const sendMsg = async (data) => {
        let res = await agentPushMessage({
            id_str: data.id_str,
            id: BotId.value
        })
        if (res.code == 1) {
            ElMessage.success(res.msg);

        }
        dialogVisibleMsg.value = false;
    }
    // 删除推送消息
    const deleteSend = async (data) => {
        let res = await agentDelPushMessage({
            id_str: data.id_str,
            id: BotId.value
        })
        if (res.code == 1) {
            ElMessage.success(res.msg);
            dialogVisibleMsg.value = false;
        }
    }

    const deleteCallback = async (data) => {
        let res = await agentDelMessage({
            id_str: data.id_str,
            id: BotId.value
        })
        if (res.code == 1) {
            getData();
            ElMessage.success(res.msg);
        }
    }
</script>

<style scoped>
    .robot {
        margin: 20px 0;
        text-align: center;
        display: flex;
        align-items: center;

        .le {
            width: 160px;
        }
    }
</style>